import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 二分搜索树测试
 *
 * @author Kevin
 * @date 2018-12-10
 */
public class BSTTest {

    public static void main(String[] args) {
        // 删除最大值和最小值
//        remove_max_min();

        // 删除操作
        remove();
    }

    private static void remove_max_min() {
        BST<Integer> bst = new BST<>();
        Random random = new Random();

        int n = 1000;

        // 测试删除最小值
        for (int i = 0; i < n; i++) {
            bst.add(random.nextInt(10000));
        }

        List<Integer> nums = new ArrayList<>();
        while (!bst.isEmpty()) {
            nums.add(bst.removeMin());
        }

        System.out.println(nums);
        for (int i = 1; i < nums.size(); i++) {
            if (nums.get(i - 1) > nums.get(i)) {
                throw new IllegalArgumentException("Error!");
            }
        }
        System.out.println("removeMin test completed.");

        // 测试删除最大值
        for (int i = 0; i < n; i++) {
            bst.add(random.nextInt(10000));
        }

        nums = new ArrayList<>();
        while (!bst.isEmpty()) {
            nums.add(bst.removeMax());
        }

        System.out.println(nums);
        for (int i = 1; i < nums.size(); i++) {
            if (nums.get(i - 1) < nums.get(i)) {
                throw new IllegalArgumentException("Error!");
            }
        }
        System.out.println("removeMax test completed.");
    }

    /**
     * 打乱数组顺序
     *
     * @param arr
     */
    private static void shuffle(Object[] arr) {
        for (int i = arr.length - 1; i >= 0; i--) {
            int pos = (int) (Math.random() * (i + 1));
            Object object = arr[pos];
            arr[pos] = arr[i];
            arr[i] = object;
        }
    }

    private static void remove() {
        BST<Integer> bst = new BST<>();
        Random random = new Random();

        int n = 3;

        for (int i = 0; i < n; i++) {
            bst.add(random.nextInt(n));
        }

        System.out.println(bst);

        // 注意, 由于随机生成的数据有重复, 所以bst中的数据数量大概率是小于n的
        // order数组中存放[0...n)的所有元素
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
        }

        // 打乱order数组的顺序
        shuffle(order);

        // 乱序删除[0...n)范围里的所有元素
        for (int i = 0; i < n; i++) {
            if (bst.contains(order[i])) {
                bst.remove(order[i]);
                System.out.println("After remove " + order[i] + ", size = " + bst.getSize());
            }
        }

        // 最终整个二分搜索树应该为空
        System.out.println(bst.getSize());
    }

}
